// index.js
const api = require('../../api/index'); // 头部引入
import Toast from '@vant/weapp/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    img: "/images/bj.jpg",
    logo: "/images/logo.png",
    showDish: false,
    showDishIndex: null,
    show: false,//商家信息弹出层
    show_shoppingCart: false,
    ShoppingCarNumber: 0,
    show_dayang: false,
    btnDisabled:true,
    status: "",
    show_User: false,
    active: 1,
    activeKey: 0,
    CategoryList: [],
    DishList: [],
    flavorValueList: [],
    ShoppingCartList: [],
    ShoppingCarSumPrice: 0,
    showStepperBtn: false,
    DishNumber: 1,
    dishFlavor: "",
    tabsId: 0,
    DishDetail: "",
    showDishDetail: false
  },
  //弹出菜品/套餐详情信息弹出层
  onShowDishDetail(e) {
    let DishDetail1 = {}
    DishDetail1 = e.currentTarget.dataset.item;
    DishDetail1.index = e.currentTarget.dataset.index;
    this.setData({
      showDishDetail: true,
      DishDetail:DishDetail1
    })
    console.log(this.data.DishDetail);
  },
  //关闭菜品/套餐详情信息弹出层
  onCloseDishDetail() {
    this.setData({
      showDishDetail: false
    })
  },
  //展示购物车信息弹出框
  onShoppingCart() {
    this.setData({
      show_shoppingCart: !this.data.show_shoppingCart
    });
  },
  //关闭购物车信息弹出框
  onCloseShoppingCart() {
    this.setData({
      show_shoppingCart: false
    });
  },
  //前往订单页面
  goOrder() {
    if (this.data.status == 0) {
      Toast.fail('本店已打烊! 于明日9点开始营业。');
      return;
    }
    let ShoppingCartList = JSON.stringify(this.data.ShoppingCartList)
    let ShoppingCarSumPrice = this.data.ShoppingCarSumPrice
    let ShoppingCarNumber = this.data.ShoppingCarNumber
    wx.navigateTo({
      url: '/pages/orderSubmit/orderSubmit?ShoppingCartList=' + ShoppingCartList + '&ShoppingCarSumPrice=' + ShoppingCarSumPrice + '&ShoppingCarNumber=' + ShoppingCarNumber,
    })
  },
  //展示菜品弹出层
  onShowDish(e) {
    // console.log(e);
    let index = e.currentTarget.dataset.index;
    let flavors = this.data.DishList[index].flavors
    let flavorsArray = []
    let flavorsArrayList = []
    flavors.forEach(item => {
      flavorsArray.push({
        name: item.name,
        value: JSON.parse(item.value)
      })
    })
    let a = []
    for (let i = 0; i < flavorsArray.length; i++) {
      let b = []
      for (let j = 0; j < flavorsArray[i].value.length; j++) {
        b.push({
          isActive: false,
          text: flavorsArray[i].value[j]
        })
      }
      a.push(b)
    }
    for (let k = 0; k < a.length; k++) {
      a[k][0].isActive = true
    }
    flavorsArray.forEach((item, index) => {
      flavorsArrayList.push({
        name: flavorsArray[index].name,
        value: a[index]
      })
    })
    // console.log("口味数组"+flavorsArray);
    console.log(flavorsArrayList);
    this.setData({
      flavorValueList: flavorsArrayList,
      showDishIndex: index,
      showDish: true,
      showDishDetail:false
    });
  },

  //菜品数量改变时触发
  onDishNumberChange(event) {
    this.setData({
      DishNumber: event.detail
    })
  },
  //选择口味
  onSelectFlavor(e) {
    console.log(e);
    let index = e.currentTarget.dataset.index; // 获取当前点击的父元素的索引
    let index_1 = e.currentTarget.dataset.index_1; // 获取当前点击的子元素的索引
    let content = e.currentTarget.dataset.content;
    var count = content[index].value.length;
    for (var i = 0; i < count; i++) {
      content[index].value[i].isActive = false
    }
    content[index].value[index_1].isActive = true;
    // 必须重新渲染数据
    this.setData({
      flavorValueList: content,
    })
  },
  //加号按钮
  onAddCart(e) {
    console.log(e);
    let CurrentShopping = e.currentTarget.dataset.item;
    let data = {}
    if (CurrentShopping.categoryType == 2) {
      data.setmealId = CurrentShopping.id;
    } else {
      // data.dishFlavor = CurrentShopping.dishFlavor;
      data.dishId = CurrentShopping.id;
    }
    api.addShoppingCart(data).then(res => {
      if (res.code == 1) {
        //增加购物车商品数量时需要重新获取菜品列表
        let id = this.data.CategoryList[this.data.activeKey].id
        let type = this.data.CategoryList[this.data.activeKey].type
        if (type == 1) {
          this.getDishList(id)
        } else {
          this.getSetmealList(id)
        }
      }
    })

    if(this.data.showDishDetail){
      let number = this.data.DishDetail.number +1
      this.setData({
        'DishDetail.number':number
      })
    }
  },
  //减号按钮
  onReduceCart(e) {
    console.log(e);

    let CurrentShopping = e.currentTarget.dataset.item;
    let data = {}
    if (CurrentShopping.categoryType == 2) {
      data.setmealId = CurrentShopping.id;
    } else {
      data.dishFlavor = CurrentShopping.dishFlavor;
      data.dishId = CurrentShopping.dishId;
    }
    api.subShoppingCart(data).then(res => {
      if (res.code == 1) {
        //减少购物车商品数量时需要重新获取菜品列表
        let id = this.data.CategoryList[this.data.activeKey].id
        let type = this.data.CategoryList[this.data.activeKey].type
        if (type == 1) {
          this.getDishList(id)
        } else {
          this.getSetmealList(id)
        }
      }
    })

  },
  //加入购物车按钮
  addShoppingCart() {
    let flavorValueList = this.data.flavorValueList;
    let dishFlavor = "";
    if (flavorValueList.length > 0) {
      for (let i = 0; i < flavorValueList.length; i++) {
        for (let j = 0; j < flavorValueList[i].value.length; j++) {
          if (flavorValueList[i].value[j].isActive) {
            if (i == 0) {
              console.log(flavorValueList[i].value[j]);
              dishFlavor += flavorValueList[i].value[j].text;
              break;
            } else {
              dishFlavor += "," + flavorValueList[i].value[j].text;
              break;
            }
          }
        }
      }
    }
    console.log(this.data.DishList);
    //传递的数据
    let data = {
      dishFlavor: dishFlavor,
      dishId: this.data.DishList[this.data.showDishIndex].id,
      number: this.data.DishNumber
    }
    // console.log(data);
    api.addShoppingCart(data).then(res => {
      if (res.code == 1) {
        this.getShoppingCartList()
        this.setData({
          showDish: false,
          DishNumber: 1
        })
      }
    })
  },
  //购物车弹出层一次添加一个购物车商品加号按钮
  onPlusCart(e) {
    console.log(e);
    let CurrentCart = e.currentTarget.dataset.item;
    let data = {}
    if (CurrentCart.setmealId != null) {
      data.setmealId = CurrentCart.setmealId;
    } else {
      data.dishFlavor = CurrentCart.dishFlavor;
      data.dishId = CurrentCart.dishId;
    }
    api.addShoppingCart(data).then(res => {
      if (res.code == 1) {
        //增加购物车商品数量时需要重新获取菜品列表
        let id = this.data.CategoryList[this.data.activeKey].id
        let type = this.data.CategoryList[this.data.activeKey].type
        if (type == 1) {
          this.getDishList(id)
        } else {
          this.getSetmealList(id)
        }
      }
    })
  },
  //购物车弹出层一次减少一个购物车商品减号按钮
  onMinusCart(e) {
    console.log(e);
    let CurrentCart = e.currentTarget.dataset.item;
    let data = {}
    if (CurrentCart.setmealId != null) {
      data.setmealId = CurrentCart.setmealId;
    } else {
      data.dishFlavor = CurrentCart.dishFlavor;
      data.dishId = CurrentCart.dishId;
    }
    api.subShoppingCart(data).then(res => {
      if (res.code == 1) {
        //减少购物车商品数量时需要重新获取菜品列表
        let id = this.data.CategoryList[this.data.activeKey].id
        let type = this.data.CategoryList[this.data.activeKey].type
        if (type == 1) {
          this.getDishList(id)
        } else {
          this.getSetmealList(id)
        }
      }
    })
  },
  //清空购物车
  cacelShoppingCart() {
    api.cleanShoppingCart().then(res => {
      if (res.code == 1) {
        //减少购物车商品数量时需要重新获取菜品列表
        let id = this.data.CategoryList[this.data.activeKey].id
        let type = this.data.CategoryList[this.data.activeKey].type
        if (type == 1) {
          this.getDishList(id)
        } else {
          this.getSetmealList(id)
        }
        this.setData({
          show_shoppingCart: false
        })
      }
    })
  },
  //分类切换
  onChange(event) {
    let id = this.data.CategoryList[event.detail].id
    let type = this.data.CategoryList[event.detail].type
    if (type == 1) {
      this.getDishList(id)
    } else {
      this.getSetmealList(id)
    }
    this.setData({
      activeKey: event.detail
    })
    console.log(this.data.activeKey);
  },
  //商家信息弹出层
  showPopup() {
    this.setData({
      show: true
    });
  },
  //联系商家
  onContact() {
    wx.makePhoneCall({
      phoneNumber: '6666666666',
      /*模拟的电话号码*/
    })
  },
  //关闭商家信息弹出层
  onClose() {
    this.setData({
      show: false
    });
  },
  //关闭商品信息弹出层
  onCloseDish() {
    this.setData({
      showDish: false
    });
  },
  //关闭店铺打烊弹出层
  onCloseDayang() {
    this.setData({
      show_dayang: false
    });
  },
  //获取用户信息
  getUserInfo() {
    //关闭提示登录框
    this.setData({
      show_User: false
    })
    wx.getUserProfile({
      desc: '获取用户信息',
      success: (res) => {
        //保存用户信息
        wx.setStorageSync('userInfo', res.userInfo)
        //获取用户授权码
        wx.login({
          success: (res) => {
            if (res.code) {
              let data = {
                code: res.code
              };
              //调用微信登录接口
              api.login(data).then((res) => {
                console.log(res);
                if (res.code == 1) {
                  wx.setStorageSync('LoginInfo', res.data)
                  wx.setStorageSync('isLogin', false)
                  this.getShopStatus();
                  this.getCategoryList();
                }
              })
            }
          }
        })
      }
    })
  },
  //用户取消登录
  cacelLogin() {
    //关闭提示登录框
    this.setData({
      show_User: false
    })
    wx.showToast({
      title: '请先登录！登录后才能点餐！',
      icon: 'error'
    })
    return;
  },
  //获取店铺状态
  getShopStatus() {
    api.status().then((res) => {
      console.log(res);
      if (res.data == 1) {
        this.setData({
          status: 1,
          show_dayang: false,
          btnDisabled:false
        })
      }else{
        this.setData({
          status: 0,
          show_dayang: true,
          btnDisabled:true
        })
      }
      return;
    })
  },
  //获取分类列表
  getCategoryList() {
    api.getCategoryList().then((res) => {
      console.log(res);
      this.setData({
        CategoryList: res.data
      })
      //首次加载页面也要获取菜品列表
      let id = this.data.CategoryList[this.data.activeKey].id
      this.getDishList(id)
    })
  },
  //根据分类id获取菜品列表
  getDishList(id) {
    api.getDishList(id).then((res) => {
      console.log("菜品列表数据：");
      console.log(res);
      this.setData({
        DishList: res.data
      })
      //根据获取菜品列表在获取购物车列表
      this.getShoppingCartList();
    })
  },
  //根据分类id获取套餐列表
  getSetmealList(id) {
    api.getSetmealList(id).then((res) => {
      console.log("套餐数据");
      console.log(res);
      this.setData({
        DishList: res.data
      })
      //根据获取菜品列表在获取购物车列表
      this.getShoppingCartList();
    })
  },
  //获取购物车列表
  getShoppingCartList() {
    api.getShoppingCartList().then((res) => {
      let ShoppingCartList = res.data;
      let ShoppingCarNumber = 0;
      let sum = 0;
      for (let i = 0; i < ShoppingCartList.length; i++) {
        //计算购物车总数量
        ShoppingCarNumber += ShoppingCartList[i].number;
        //计算购物车总价格
        sum += ShoppingCartList[i].number * ShoppingCartList[i].amount
      }
      sum = parseFloat(sum.toFixed(2))

      console.log("购物车列表数据：");
      console.log(ShoppingCartList);
      let newDishList = this.data.DishList;
      // console.log(newDishList);
      for (let i = 0; i < newDishList.length; i++) {
        let number = 0;
        for (let j = 0; j < ShoppingCartList.length; j++) {
          if ((newDishList[i].id == ShoppingCartList[j].dishId) || (newDishList[i].id == ShoppingCartList[j].setmealId)) {
            number += ShoppingCartList[j].number
          }
        }
        newDishList[i].number = number
        newDishList[i].categoryType = this.data.CategoryList[this.data.activeKey].type
      }
      // console.log(newDishList);
      this.setData({
        DishList: newDishList,
        ShoppingCartList,
        ShoppingCarNumber,
        ShoppingCarSumPrice: sum
      })
      // console.log(this.data.DishList);
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   let isLogin = wx.getStorageSync('isLogin');
   console.log(isLogin);
   if(isLogin){
     this.setData({
      show_User:true
     })
   }else{
    this.getShopStatus();
   }
    // if (!this.data.show_User) {
    //   this.getShopStatus();
    //   // this.getCategoryList();
    //   //this.getShoppingCartList();
    // }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (!this.data.show_User) {
      this.getShopStatus();
      this.getCategoryList();
      //this.getShoppingCartList();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      showDish: false,
      show_shoppingCart: false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})